#pragma once

#include <unistd.h>
#include <cstring>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include "log.hpp"

enum
{
    SOCKET_ERR = 1,
    BIND_ERR,
    LISTEM_ERR,
};

const int backlog = 10;

class Sock
{
public:
    Sock()
    {}

    ~Sock()
    {}
    void Socket()
    {
        _sockfd = socket(AF_INET, SOCK_STREAM, 0);
        if(_sockfd < 0)
        {
            lg(Fatal, "socket err, sockfd: %d", _sockfd);
            exit(SOCKET_ERR);
        }
        lg(Info, "socket success, sockfd: %d", _sockfd);
    }

    void Bind(uint32_t port)
    {
        
        struct sockaddr_in local;
        local.sin_family = AF_INET;

        local.sin_port = htons(port);
        local.sin_addr.s_addr = INADDR_ANY;
        if(bind(_sockfd, (struct sockaddr*)&local, sizeof(local)) < 0)
        {
            lg(Fatal, "Bind err, errno: %d, errno string %s", errno, strerror(errno));
            exit(BIND_ERR);
        }
        lg(Info, "Bind success, errno: %d, errno string %s", errno, strerror(errno));
    }

    void Listen()
    {
        if(listen(_sockfd, backlog) < 0)
        {
            lg(Fatal, "Listen err, errno: %d, errno string %s", errno, strerror(errno));
            exit(LISTEM_ERR);
        }
        lg(Info, "Listen success, errno: %d, errno string %s", errno, strerror(errno));

    }

    
    int Accept(std::string& client_ip, uint16_t& client_port)
    {
        struct sockaddr_in client;
        socklen_t len = sizeof(client);
        int newfd = accept(_sockfd, (struct sockaddr*)&client, &len);

        if(newfd < 0)
        {
            lg(Warning, "accept errno: %d, errno string %s", errno, strerror(errno));
            return -1;
        }

        char ipstr[64];
        inet_ntop(AF_INET, &client.sin_addr, ipstr, sizeof(ipstr));
        client_ip = ipstr;
        client_port = ntohs(client.sin_port);

        return newfd;
    }

    bool Connect(std::string& ip, uint16_t port)
    {
        struct sockaddr_in server;
        server.sin_family = AF_INET;
        server.sin_port = htons(port);
        inet_pton(AF_INET, ip.c_str(), &(server.sin_addr));

        int n = connect(_sockfd, (struct sockaddr*)&server, sizeof(server));
        if(n < 0)
        {
            std::cout << "connect err..." << std::endl;
            return false;
        }

        std::cout << "connect success..." << std::endl;
        return true;
    }
    
    void Close()
    {
        close(_sockfd);
    }

    int GetSockfd()
    {
        return _sockfd;
    }

private:

    int _sockfd;
};